package com.sjb.cp.manager.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import com.sjb.cp.config.COSConfig;
import com.sjb.cp.exception.BusinessException;
import com.sjb.cp.exception.ErrorCode;
import com.sjb.cp.manager.CosManager;
import com.sjb.cp.model.dto.file.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @Author:sjb
 * @CreateTime:2025-01-20
 * @Description: 图片上传模版抽象类
 * @Version：1.0
 */
@Slf4j
public abstract class PictureUploadTemplate {

    @Resource
    protected CosManager cosManager;

    @Resource
    protected COSConfig cosConfig;

    //校验文件
    //获取上传地址
    //获取本地临时文件
    //上传到对象存储
    //封装解析得到的图片信息
    //清理临时文件

    /**
     * 上传图片
     * @param inputSource
     * @param uploadPathPrefix
     * @return
     */
    public final UploadPictureResult uploadPicture(Object inputSource,String uploadPathPrefix){
        // 校验文件
        validPicture(inputSource);
        // 获取文件上传地址
        String uuid = RandomUtil.randomString(16);
        String originFilename = getOriginFilename(inputSource);

        String uploadFilename = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid,
                FileUtil.getSuffix(originFilename));

        String uploadPath = String.format("%s/%s", uploadPathPrefix, uploadFilename);

        // 获取本地临时文件
        File file = null;
        try {
           file =  File.createTempFile(uploadPath, null);
           // 处理文件来源
            processFile(inputSource,file);

            // 上传图片到图像存储
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            List<CIObject> objectList = processResults.getObjectList();
            if (CollUtil.isNotEmpty(objectList)){
                CIObject compressedCiObject = objectList.get(0);
                // 缩略图默认等于压缩图
                CIObject thumbnailCiObject = compressedCiObject;
                // 有生成缩略图，才得到缩略图
                if (objectList.size() > 1) {
                    thumbnailCiObject = objectList.get(1);
                }
                return buildCompressResult(originFilename,compressedCiObject,thumbnailCiObject,imageInfo);
            }
            return buildResult(originFilename,file,uploadPath,imageInfo);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            // 清理临时文件
            deleteTempFile(file);
        }
    }

    /**
     * 校验输入源（本地文件或 URL）
     */
    protected abstract void validPicture(Object inputSource);

    /**
     * 获取输入源的原始文件名
     */
    protected abstract String getOriginFilename(Object inputSource);

    /**
     * 处理输入源并生成本地临时文件
     */
    protected abstract void processFile(Object inputSource, File file) throws Exception;


    /**
     * 封装返回结果-原图
     */
    private UploadPictureResult buildResult(String originFilename, File file, String uploadPath, ImageInfo imageInfo) {
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        int picWidth = imageInfo.getWidth();
        int picHeight = imageInfo.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        uploadPictureResult.setPicName(FileUtil.mainName(originFilename));
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(imageInfo.getFormat());
        uploadPictureResult.setPicSize(FileUtil.size(file));
        uploadPictureResult.setPicColor(imageInfo.getAve());
        uploadPictureResult.setUrl(cosConfig.getHost() + "/" + uploadPath);
        return uploadPictureResult;
    }

    /**
     * 封装压缩后的结果图片
     * @param originFileName
     * @param ciObject
     * @return
     */
    private UploadPictureResult buildCompressResult(String originFileName,CIObject ciObject,
                                                    CIObject thumbnailCiObject,ImageInfo imageInfo){
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        int picWidth = ciObject.getWidth();
        int picHeight = ciObject.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        uploadPictureResult.setPicName(FileUtil.mainName(originFileName));
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(ciObject.getFormat());
        uploadPictureResult.setPicSize(ciObject.getSize().longValue());
        uploadPictureResult.setPicColor(imageInfo.getAve());

        // 设置图片为压缩后的地址
        uploadPictureResult.setUrl(cosConfig.getHost() + "/" + ciObject.getKey());
        // 设置缩略图
        uploadPictureResult.setThumbnailUrl(cosConfig.getHost() + "/" + thumbnailCiObject.getKey());
        return uploadPictureResult;
    }

    /**
     * 清理临时文件
     * @param file
     */
    public void deleteTempFile(File file){
        if (file == null){
            return;
        }
        boolean deleted = file.delete();
        if (!deleted){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"清理临时文件失败");
        }
    }
}
